package com.wzdigit.wms.raw.service.mid;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzdigit.mes.basic.api.BasicDataItemDetailApi;
import com.wzdigit.mes.basic.api.BasicVendorApi;
import com.wzdigit.mes.basic.dto.DataItemDetailDTO;
import com.wzdigit.mes.basic.dto.VendorDTO;
import com.wzdigit.wms.basic.client.response.basic.SkuBaseResponse;
import com.wzdigit.wms.basic.client.response.basic.SkuResponse;
import com.wzdigit.wms.basic.domain.asn.AsnDtl;
import com.wzdigit.wms.basic.domain.asn.AsnHeader;
import com.wzdigit.wms.basic.domain.basic.Sku;
import com.wzdigit.wms.basic.domain.mapping.CodeMapping;
import com.wzdigit.wms.basic.domain.mid.JobSyncErrorData;
import com.wzdigit.wms.basic.domain.transfer.GdnDtl;
import com.wzdigit.wms.basic.domain.transfer.GdnHeader;
import com.wzdigit.wms.basic.enums.*;
import com.wzdigit.wms.basic.mapper.core.basic.SkuMapper;
import com.wzdigit.wms.basic.mapper.core.mid.JobSyncErrorDataMapper;
import com.wzdigit.wms.basic.mapper.core.order.AsnDtlMapper;
import com.wzdigit.wms.basic.mapper.core.order.AsnHeaderMapper;
import com.wzdigit.wms.basic.mapper.core.transfer.GdnDtlMapper;
import com.wzdigit.wms.basic.mapper.core.transfer.GdnHeaderMapper;
import com.wzdigit.wms.raw.constant.SyncTypeConstant;
import com.wzdigit.wms.raw.domain.dto.HouseQaStatus;
import com.wzdigit.wms.raw.domain.dto.IfPullHeaderDto;
import com.wzdigit.wms.raw.domain.mid.IfPullDtl;
import com.wzdigit.wms.raw.domain.mid.IfPullHeader;
import com.wzdigit.wms.raw.exception.SyncException;
import com.wzdigit.wms.raw.mapper.mid.IfPullDtlMapper;
import com.wzdigit.wms.raw.mapper.mid.IfPullHeaderMapper;
import net.dreamlu.mica.core.utils.BeanUtil;
import net.dreamlu.mica.core.utils.CollectionUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 接口中间表-采购订单 同步 采购订单
 * </p>
 *
 * @author chao shuai
 * @since 2021-06-10
 */
@Service
public class IfPullHeaderService {

    @Autowired
    private IfPullHeaderMapper ifPullHeaderMapper;

    @Autowired
    private IfPullDtlMapper ifPullDtlMapper;

    @Autowired
    private GdnHeaderMapper gdnHeaderMapper;

    @Autowired
    private GdnDtlMapper gdnDtlMapper;

    @Autowired
    private AsnHeaderMapper asnHeaderMapper;

    @Autowired
    private AsnDtlMapper asnDtlMapper;

    @Autowired
    private JobSyncErrorDataMapper jobSyncErrorDataMapper;

    @Reference(version = "${dubbo.consumers.basic.vendor.api:1.0.0}", check = false, timeout = 300000)
    private BasicVendorApi  basicVendorApi;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private SyncErrorDataService syncErrorDataService;

    @Autowired
    MappingHouseService mappingHouseService;

    @Reference(version = "${dubbo.consumers.basic.data.item.detail.api:1.0.0}", check = false, timeout = 300000)
    private BasicDataItemDetailApi dataItemDetailApi;


    @Value(value = "${default_owner.code}")
    private String DEFAULT_OWNER;

    @Value(value = "${default_owner.name}")
    private String DEFAULT_OWNER_NAME;



    private final String ASN_NO = "ASN_R04";

    private final String syncType = SyncTypeConstant.IF_PULL_TO_GDN_OR_ASN;

    public List<IfPullHeaderDto> selectSyncData() {
        ArrayList<IfPullHeaderDto> ifPullHeaderDtos = new ArrayList<>();
        QueryWrapper<IfPullHeader> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("Attribute10","1").or().isNull("Attribute10");
        List<IfPullHeader> selectSyncData = ifPullHeaderMapper.selectList(queryWrapper);
        if (!CollectionUtil.isEmpty(selectSyncData)) {
            for (IfPullHeader ifPullHeader : selectSyncData) {
                IfPullHeaderDto ifPullHeaderDto = new IfPullHeaderDto();
                BeanUtil.copyNonNull(ifPullHeader, ifPullHeaderDto);
                List<IfPullDtl> ifSalesreturnDtls = ifPullDtlMapper.selectList(new QueryWrapper<>(
                        new IfPullDtl().setIfPullHeaderId(ifPullHeader.getIfPullHeaderId())
                ));
                ifPullHeaderDto.setIfPullDtlList(ifSalesreturnDtls);
                ifPullHeaderDtos.add(ifPullHeaderDto);
            }

        }
        return ifPullHeaderDtos;
    }




    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void syncDataGdn(IfPullHeaderDto data, boolean isSyncError) throws Exception {
        String pullNo = data.getPullNo(); //委外单号--》发货单号or收货通知单号
        //查询供应商信息
        VendorDTO vendor = basicVendorApi.getVendorByCode(data.getLifnr());
        if (vendor == null||vendor.getVendorId()==null) {
            throw new SyncException(syncType, pullNo, "供应商" + data.getLifnr() + "不存在");
        }
        List<IfPullDtl> ifPullDtlList = data.getIfPullDtlList();

        GdnHeader gdnHeader = new GdnHeader();
        //同步主表信息
        gdnHeader.setGdnNo(data.getPullNo());
        gdnHeader.setGdnType(GdnTypeEnum.D12.code);
        gdnHeader.setConsigneeId(vendor.getVendorId().longValue());
        gdnHeader.setConsigneeName(vendor.getVendorName());
        gdnHeader.setFactory(data.getWerks());
        gdnHeader.setGdnCreateUser(data.getCreateUser());
        gdnHeader.setGdnCreateTime(data.getCreateTime());
        gdnHeader.setShipDate(new Date());

        DataItemDetailDTO dataItem = dataItemDetailApi.getDefaultDataItemDetailByCode(DEFAULT_OWNER);

        gdnHeader.setOwner(dataItem == null || dataItem.getItemValue() == null ? 0: Integer.valueOf(dataItem.getItemValue()));
        GdnHeader gdnHeaderRecord = gdnHeaderMapper.selectOne(new QueryWrapper<>(new GdnHeader().setGdnNo(pullNo)));
        if (gdnHeaderRecord == null) {
            gdnHeader.setCreateUser("system");
            gdnHeader.setCreateTime(new Date());
            gdnHeader.setStatus(GdnHeaderStatusEnum.CREATE.getCode());//新建状态
            gdnHeaderMapper.insert(gdnHeader);
        } else {
            gdnHeader.setModifyTime(new Date());
            gdnHeader.setModifyUser("system");
            gdnHeader.setGdnHeaderId(gdnHeaderRecord.getGdnHeaderId());
            gdnHeaderMapper.updateById(gdnHeader);
        }
        //同步明细

        Integer maxLineNo = gdnDtlMapper.selectMaxLineId(gdnHeader.getGdnHeaderId());
        if(maxLineNo == null){
            maxLineNo =  0;
        }

        for (IfPullDtl ifPullDtl : ifPullDtlList) {
            //查询SKUID
            SkuBaseResponse sku = skuMapper.getSkuByCode(ifPullDtl.getItemCode());
            if(sku==null||sku.getSkuId()==null){
                throw new SyncException(syncType, pullNo, "物料编码" + ifPullDtl.getItemCode() + "不存在");
            }
            //处理仓库信息
            //获取仓库
            HouseQaStatus houseQaStatus = mappingHouseService.getWmsHourseIdBySapHourseCode(ifPullDtl.getReceivingWarehouseCode());
            if(houseQaStatus==null){
                throw new SyncException(syncType, pullNo, "SAP仓库编码" + ifPullDtl.getReceivingWarehouseCode() + "无法转换成WMS仓库");
            }

            GdnDtl gdnDtl = new GdnDtl();
            gdnDtl.setGdnHeaderId(gdnHeader.getGdnHeaderId());
            gdnDtl.setSourceShipNoticeItem(ifPullDtl.getPullLineNo());//行号
            gdnDtl.setSkuId(sku.getSkuId());
            gdnDtl.setUnit(ifPullDtl.getUomCode());
            gdnDtl.setOrderQty(ifPullDtl.getQuantity());
            gdnDtl.setWhsId(houseQaStatus.getWhsId());
            gdnDtl.setComments(ifPullDtl.getRemark());
            gdnDtl.setCreateTime(ifPullDtl.getCreateTime());
            gdnDtl.setCreateUser(ifPullDtl.getCreateUser());

            GdnDtl gdnDtlRecord = gdnDtlMapper.selectOne(new QueryWrapper<>(new GdnDtl().setGdnHeaderId(gdnHeader.getGdnHeaderId()).setSourceShipNoticeItem(ifPullDtl.getPullLineNo())));
            if (gdnDtlRecord == null) {
                gdnDtl.setCreateUser("system");
                gdnDtl.setCreateTime(new Date());
                gdnDtl.setStatus( GdnDtlStatusEnum.CREATE.getCode());//新建状态
                gdnDtl.setQaStatus(QaStatusEnum.OK.code);
                gdnDtl.setGdnLineNo(++maxLineNo);
                try {
                    gdnDtlMapper.insert(gdnDtl);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, pullNo, e.getMessage());
                }
            } else {
                gdnDtl.setModifyUser("system");
                gdnDtl.setModifyTime(new Date());
                gdnDtl.setGdnDtlId(gdnDtlRecord.getGdnDtlId());
                try {
                    gdnDtlMapper.updateById(gdnDtl);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, pullNo, e.getMessage());
                }
            }
            int row = ifPullHeaderMapper.updateFlagById(data.getIfPullHeaderId());
            //检查是否有同步失败的记录，有则更新为成功
            JobSyncErrorData jobSyncErrorData = jobSyncErrorDataMapper.getSyncErrorDataByTypeAndCode(syncType, pullNo);
            if (jobSyncErrorData != null && 0 == jobSyncErrorData.getIsSuccess()) {
                syncErrorDataService.updateSuccessByCode(syncType, pullNo);
            }
        }

    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void syncDataAsn(IfPullHeaderDto data, boolean isSyncError) throws Exception {
        String pullNo = data.getPullNo(); //委外单号--》发货单号or收货通知单号
        //查询供应商信息
        VendorDTO vendor = basicVendorApi.getVendorByCode(data.getLifnr());
        if (vendor == null||vendor.getVendorId()==null) {
            throw new SyncException(syncType, pullNo, "供应商" + data.getLifnr() + "不存在");
        }
        List<IfPullDtl> ifPullDtlList = data.getIfPullDtlList();

        AsnHeader asnHeader = new AsnHeader();
        //同步主表信息
        asnHeader.setAsnNo(data.getPullNo());
        asnHeader.setAsnType(AsnTypeEnum.R12.code);
        asnHeader.setVendorId(vendor.getVendorId());
        asnHeader.setFactory(data.getWerks());
        asnHeader.setAsnCreateUser(data.getCreateUser());
        asnHeader.setAsnCreateTime(data.getCreateTime());
        DataItemDetailDTO dataItem = dataItemDetailApi.getDataItemDetailByPCodeAndName(DEFAULT_OWNER, DEFAULT_OWNER_NAME);
        asnHeader.setOwner(dataItem == null || dataItem.getItemValue() == null ? 0: Integer.valueOf(dataItem.getItemValue()));

        AsnHeader asnHeaderRecord = asnHeaderMapper.selectOne(new QueryWrapper<>(new AsnHeader().setAsnNo(pullNo)));
        if (asnHeaderRecord == null) {
            asnHeader.setCreateUser("system");
            asnHeader.setCreateTime(new Date());
            asnHeader.setStatus(( AsnHeaderStatusEnum.CREATE.code));  //到货通知单状态
            asnHeader.setQcStatus( QaStatusEnum.OK.code); //质检状态
            asnHeader.setReleaseStatus(AsnHeaderStatusEnum.CANCEL.code); //ASN释放状态
            asnHeader.setPriority(0); //优先级
            asnHeaderMapper.insert(asnHeader);
        } else {
            asnHeader.setModifyTime(new Date());
            asnHeader.setModifyUser("system");
            asnHeader.setAsnHeaderId(asnHeaderRecord.getAsnHeaderId());
            asnHeaderMapper.updateById(asnHeader);
        }
        //同步明细

        Integer asnLineNo = 0;

        for (IfPullDtl ifPullDtl : ifPullDtlList) {
            SkuBaseResponse sku = skuMapper.getSkuByCode(ifPullDtl.getItemCode());
            if(sku==null||sku.getSkuId()==null){
                throw new SyncException(syncType, pullNo, "物料编码" + ifPullDtl.getItemCode() + "不存在");
            }
            //处理仓库信息

            //获取仓库
            HouseQaStatus houseQaStatus = mappingHouseService.getWmsHourseIdBySapHourseCode(ifPullDtl.getReceivingWarehouseCode());
            if(houseQaStatus==null){
                throw new SyncException(syncType, pullNo, "SAP仓库编码" + ifPullDtl.getReceivingWarehouseCode() + "无法转换成WMS仓库");
            }

            AsnDtl asnDtl = new AsnDtl();
            asnDtl.setAsnHeaderId(asnHeader.getAsnHeaderId());
            asnDtl.setAsnNo(asnHeader.getAsnNo());
            asnDtl.setAsnLineNo(ifPullDtl.getPullLineNo());
            asnDtl.setSkuId(sku.getSkuId());
            asnDtl.setSkuDesc(sku.getDescCn());
            asnDtl.setUnit(ifPullDtl.getUomCode());
            asnDtl.setOrderQty(ifPullDtl.getQuantity());
            asnDtl.setOrderQtyEa(ifPullDtl.getQuantity());
            asnDtl.setWhsId(houseQaStatus.getWhsId());
            asnDtl.setComments(ifPullDtl.getRemark());
            asnDtl.setCreateTime(ifPullDtl.getCreateTime());
            asnDtl.setCreateUser(ifPullDtl.getCreateUser());




            AsnDtl asnDtlRecord = asnDtlMapper.selectOne(new QueryWrapper<>(new AsnDtl().setAsnHeaderId(asnHeader.getAsnHeaderId()).setAsnLineNo(ifPullDtl.getPullLineNo())));
            if (asnDtlRecord == null) {
                asnDtl.setCreateUser("system");
                asnDtl.setCreateTime(new Date());
                asnDtl.setStatus(GdnDtlStatusEnum.CREATE.getCode());//新建状态
                asnDtl.setQaStatus(QaStatusEnum.OK.code);
                asnDtl.setQcStatus(QcStatusEnum.全部质检.getCode());
                try {
                    asnDtlMapper.insert(asnDtl);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, pullNo, e.getMessage());
                }
            } else {
                asnDtl.setModifyUser("system");
                asnDtl.setModifyTime(new Date());
                asnDtl.setAsnDtlId(asnDtlRecord.getAsnDtlId());
                try {
                    asnDtlMapper.updateById(asnDtl);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, pullNo, e.getMessage());
                }
            }
            int row = ifPullHeaderMapper.updateFlagById(data.getIfPullHeaderId());
            //检查是否有同步失败的记录，有则更新为成功
            JobSyncErrorData jobSyncErrorData = jobSyncErrorDataMapper.getSyncErrorDataByTypeAndCode(syncType, pullNo);
            if (jobSyncErrorData != null && 0 == jobSyncErrorData.getIsSuccess()) {
                syncErrorDataService.updateSuccessByCode(syncType, pullNo);
            }
        }

    }

}
